//
//  Find_ActivityView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/10.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "Find_ActivityView.h"
#import "Find_ActivityTableViewCell.h"
#import "Find_activityClassificationCell.h"
#import "AFNetworking.h"
#import "Find_Activity_Model.h"
#import "Find_Activity_Top_Model.h"
#import "UIImageView+WebCache.h"

@interface Find_ActivityView ()<UITableViewDelegate, UITableViewDataSource, MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
}
@property (strong, nonatomic) AMPopTip *popTip;

@end

@implementation Find_ActivityView
- (instancetype)initWithFrame:(CGRect)frame popTip:(AMPopTip *)popTip
{
    self = [super initWithFrame:frame];
    if (self) {
        self.activityArray = [[NSMutableArray alloc] init];
        self.activityTopPartArray = [[NSMutableArray alloc] init];
        [self createTableView];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"find_activity"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadActivityData:content pag:1];
            page = 1;
        } else {
        }
        [header beginRefreshing];
        self.popTip = popTip;
    }
    return self;
}
- (void)hideFooterView
{
    fotter.hidden = YES;
}
- (void)createTableView
{
    self.ActivityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) style:UITableViewStylePlain];
//    _ActivityTableView.backgroundColor = [UIColor blueColor];
    _ActivityTableView.delegate = self;
    _ActivityTableView.dataSource = self;
    _ActivityTableView.showsVerticalScrollIndicator = NO;
    _ActivityTableView.showsHorizontalScrollIndicator = NO;

    _ActivityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:_ActivityTableView];
    
    if ([self.ActivityTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.ActivityTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.ActivityTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.ActivityTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    header = [MJRefreshHeaderView header];
    header.scrollView = _ActivityTableView;
    header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _ActivityTableView;
    fotter.delegate = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _activityTopPartArray.count;
    } else {
        return _activityArray.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    } else {
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
        sectionHeader.backgroundColor = [UIColor colorWithRed:0.965 green:0.965 blue:0.965 alpha:1.00];
//        UIView *blackline = [[UIView alloc] initWithFrame:CGRectMake(0, 13, tableView.bounds.size.width, 4)];
//        blackline.backgroundColor = [UIColor blackColor];
//        [sectionHeader addSubview:blackline];
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, sectionHeader.frame.size.width, 30)];
        title.textColor = [UIColor blackColor];
        title.font = [UIFont boldSystemFontOfSize:15];
        title.backgroundColor = [UIColor clearColor];
        title.textAlignment = NSTextAlignmentCenter;
        title.text = @ "——————  NEW  ——————";
        [sectionHeader addSubview:title];
        return sectionHeader;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return (self.bounds.size.width - 40) / 3 + 200 + 50;
    } else {
        return tableView.frame.size.width / 2 * 1.45;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *TableIdentifer = @"classification";
        Find_activityClassificationCell *classificationCell = [tableView dequeueReusableCellWithIdentifier:TableIdentifer];
        NSArray *array =_activityTopPartArray[indexPath.row];
        NSInteger count = array.count;
        if (classificationCell == nil) {
            classificationCell = [[Find_activityClassificationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifer count:count];
        }
        classificationCell.dataArray = _activityTopPartArray[indexPath.row];
        classificationCell.selectionStyle = UITableViewCellSelectionStyleNone;
        classificationCell.block = ^(NSString *type_id){
            _moreLabxBlock(type_id);
        };
        return classificationCell;
    } else {
        static NSString *ActivityTableIdentifer = @"activity";
        Find_ActivityTableViewCell *activityCell = [tableView dequeueReusableCellWithIdentifier:ActivityTableIdentifer];
        if (activityCell == nil) {
            activityCell = [[Find_ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ActivityTableIdentifer];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (_activityArray.count > 0) {
            Find_Activity_Model *leftModel = [_activityArray[indexPath.row] valueForKey:@"left"];
            Find_Activity_Model *rightModel = [_activityArray[indexPath.row] valueForKey:@"right"];
            [activityCell.leftButton.bigImage setImageWithURL:[NSURL URLWithString:leftModel.cover]];
            activityCell.leftButton.workName.text = leftModel.title;
            activityCell.leftButton.typeLable.text = leftModel.type_name;
            activityCell.leftButton.loveImg.image = [UIImage imageNamed:@"love_gray_button"];
            activityCell.leftButton.loveLab.text = leftModel.love_count;
            activityCell.leftButton.contentImg.image = [UIImage imageNamed:@"Find_labx_content"];
            activityCell.leftButton.contentLab.text = leftModel.comm_count;
            activityCell.leftButton.price.text = [NSString stringWithFormat:@"%@元",leftModel.price];
            
            if (rightModel.cover.length > 0 || rightModel.cover != NULL) {
                [activityCell.rightButton.bigImage setImageWithURL:[NSURL URLWithString:rightModel.cover]placeholderImage:[UIImage imageNamed:@"placeholderImage"] ];
                activityCell.rightButton.workName.text = rightModel.title;
                activityCell.rightButton.typeLable.text = rightModel.type_name;
                activityCell.rightButton.loveImg.image = [UIImage imageNamed:@"love_gray_button"];
                activityCell.rightButton.loveLab.text = rightModel.love_count;
                activityCell.rightButton.contentImg.image = [UIImage imageNamed:@"Find_labx_content"];
                activityCell.rightButton.contentLab.text = rightModel.comm_count;
                activityCell.rightButton.price.text = [NSString stringWithFormat:@"%@元",rightModel.price];
            }
            activityCell.rightBlock = ^() {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:rightModel.id];
            };
            activityCell.leftBlock = ^() {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:leftModel.id];
            };
        }
        return activityCell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.popTip isVisible]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hidePopview" object:nil];
    } else {
        if (indexPath.section == 1) {
            Find_Activity_Model *model = _activityArray[indexPath.row];
            NSString *workid = model.id;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:workid];
        }
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    // Get visible cells on table view.
//    NSArray *visibleCells = [self.ActivityTableView visibleCells];
//    
//    for (Find_ActivityTableViewCell *cell in visibleCells) {
//        [cell cellOnTableView:self.ActivityTableView didScrollOnView:self];
//    }
//}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_activityTopPartArray removeAllObjects];
        [_activityArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            [self hideFooterView];
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{

}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/discover?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];

     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadActivityData:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
//            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [refreshView endRefreshing];
    }];
   
}
- (void)reloadActivityData:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    NSMutableArray *tempArray= [[NSMutableArray alloc] init];
    for (NSDictionary *dict in dic) {
        Find_Activity_Model *model = [[Find_Activity_Model alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [tempArray addObject:model];
        
    }
//    此出必须合并数组
    for (int i = 0; i <= tempArray.count; i=i+2) {
        if (i<tempArray.count) {
            if (i + 1 >= tempArray.count && i == tempArray.count - 1) {
                NSDictionary *tempDic = [[NSDictionary alloc] initWithObjectsAndKeys:tempArray[i],@"left", nil];
                [_activityArray addObject:tempDic];
                
            } else {
                NSDictionary *tempDic = [[NSDictionary alloc] initWithObjectsAndKeys:tempArray[i],@"left",tempArray[i + 1],@"right", nil];
                [_activityArray addObject:tempDic];
            }
        } else {
            
        }
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        if (pag == 1 && [meta valueForKey:@"labx1"]) {
            NSArray *array1 = [meta valueForKey:@"labx1"];
            NSMutableArray *mArray1 = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array1) {
                Find_Activity_Top_Model *model = [[Find_Activity_Top_Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray1 addObject:model];
            }
            NSArray *array2 = [meta valueForKey:@"labx2"];
            NSMutableArray *mArray2 = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array2) {
                Find_Activity_Top_Model *model = [[Find_Activity_Top_Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray2 addObject:model];
            }
            NSArray *array3 = [meta valueForKey:@"labx3"];
            NSMutableArray *mArray3 = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array3) {
                Find_Activity_Top_Model *model = [[Find_Activity_Top_Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray3 addObject:model];
            }
            NSArray *array4 = [meta valueForKey:@"labx4"];
            NSMutableArray *mArray4 = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array4) {
                Find_Activity_Top_Model *model = [[Find_Activity_Top_Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray4 addObject:model];
            }
            if (mArray1.count >= 3) {
                [_activityTopPartArray addObject:mArray1];
            }
            if (mArray2.count >= 3) {
                [_activityTopPartArray addObject:mArray2];
            }
            if (mArray3.count >= 3) {
                [_activityTopPartArray addObject:mArray3];
            }
            if (mArray4.count >= 3) {
                [_activityTopPartArray addObject:mArray4];
            }
        }
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            
        }
    }
    [_ActivityTableView reloadData];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
